<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use think\Db;

class  Iphone extends Base {
    function validate_apple_pay($receipt_data){
        /**
         * 21000 App Store不能读取你提供的JSON对象
         * 21002 receipt-data域的数据有问题
         * 21003 receipt无法通过验证
         * 21004 提供的shared secret不匹配你账号中的shared secret
         * 21005 receipt服务器当前不可用
         * 21006 receipt合法，但是订阅已过期。服务器接收到这个状态码时，receipt数据仍然会解码并一起发送
         * 21007 receipt是Sandbox receipt，但却发送至生产系统的验证服务
         * 21008 receipt是生产receipt，但却发送至Sandbox环境的验证服务
         */
        function acurl($receipt_data, $sandbox=0){
            //小票信息
            $POSTFIELDS = array("receipt-data" => $receipt_data);
            $POSTFIELDS = json_encode($POSTFIELDS);

            //正式购买地址 沙盒购买地址
//            $url_buy     = "https://buy.itunes.apple.com/verifyReceipt";
            $url_buy     = "https://buy.itunes.apple.com/verifyReceipt";
            $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
            $url = $sandbox ? $url_sandbox : $url_buy;
            //$url = $url_sandbox;

            //简单的curl
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
            $result = curl_exec($ch);
            curl_close($ch);
            return $result;
        }
        // 验证参数
        if (strlen($receipt_data)<20){
            $result=array(
                'status'=>false,
                'message'=>'非法参数'
            );
            return $result;
        }
        // 请求验证
        $html = acurl($receipt_data);
        $data = json_decode($html,true);

        // 如果是沙盒数据 则验证沙盒模式
        if($data['status']=='21007'){
            // 请求验证
            $html = acurl($receipt_data, 1);
            $data = json_decode($html,true);
            $data['sandbox'] = '1';
        }

        if (isset($_GET['debug'])) {
            exit(json_encode($data));
        }

        // 判断是否购买成功
        if(intval($data['status'])===0){
            $result=array(
                'status'=>true,
                'message'=>'购买成功'
            );
        }else{
            $result=array(
                'status'=>false,
                'message'=>'购买失败 status:'.$data['status']
            );
        }
        return $result;
    }

    public function apppay()
    {
        $param = $_POST['param'];
        $res = $this->validate_apple_pay($param);
        if($res['status']){
            // 验证通过 此处可以是修改数据库订单状态等操作
            $num = $_POST['order_number'];
            $order = Db::table('up_order')->where('order_number', $num)->find();
            //1、支付成功改状态
            $update = array();
            $update['order_status'] = 2;
            $update['order_back_transaction_id'] = $_POST['transaction_id'];
            $update['order_paytime'] = date('Y-m-d H:i:s');
            Db::startTrans();
            try{
                Db::table('up_order')
                    ->where('order_number', $num)
                    ->update($update);
                //1-2、改会员时长或包数量
                $type = $order['order_type'];//1是会员购买 2是置顶包 3是刷新包
                if($type == 1){
                    $update2 = array();
                    $update2['user_auth'] = $order['order_auth_type'];
                    $update2['user_auth_start'] = $order['order_auth_begin'];
                    $update2['user_auth_end'] = $order['order_auth_end'];
                    Db::table('up_u_user')
                        ->where('user_id',$order['order_user_id'])
                        ->update($update2);
                }elseif ($type == 2){
                    Db::table('up_u_user')
                        ->where('user_id',$order['order_user_id'])
                        ->setInc('user_mytop');
                }elseif ($type == 3){
                    Db::table('up_u_user')
                        ->where('user_id',$order['order_user_id'])
                        ->setInc('user_myfresh');
                }else{
                    Db::rollback();
                    return json_encode(['status'=>0,'msg'=>'购买失败']);
                }
                Db::commit();
                return json_encode(['status'=>200,'msg'=>'购买成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json_encode(['status'=>0,'msg'=>'购买失败']);
            }
        }else{
            // 验证不通过
            return json_encode(['status'=>0,'msg'=>'购买失败']);
        }
    }

    /**
     * 确认订单页——支付
     * 哪一类型：which（1是会员购买 2是置顶包 3是刷新包）（bag对应表的id）
     * 如果是会员：authtype（买的是何种会员(2季度  3半年  4一年）
     * 哪方支付：type（1是支付宝  2是微信）
     */
    public function getPayInfo()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $number = date('YmdHis') . rand(1000000,9999999);
        $today = date('Y-m-d');
        $order = array();
        $order['order_number'] = $number;
        $order['order_user_id'] = $user_id;
        $order['order_type'] = $which;
        $order['order_date'] = $today;
        $order['order_time'] = date('Y-m-d H:i:s');
        //1、买的是会员还是包
        if($which == 1){
            $money = Db::table('up_member_price')
                ->where('mp_auth',$authtype)
                ->where('mp_phone',2)
                ->value('mp_price');
            $order['order_money'] = $money;
            $order['order_auth_type'] = $authtype;
            //1-1：如果是会员算一下会员日期
            $user = Db::table('up_u_user')
                ->where('user_id', $user_id)
                ->field('user_auth,user_auth_start,user_auth_end')
                ->find();
            if($authtype == 2){$many = 3;}
            if($authtype == 3){$many = 6;}
            if($authtype == 4){$many = 12;}
            if($user['user_auth'] > 1){//往后延
                $order['order_auth_begin'] = $user['user_auth_start'];
                $order['order_auth_end'] = $this->getNextMonthDays($user['user_auth_end'],$many+1);
            }else{//新买的和升级的都是从今天开始
                $order['order_auth_begin'] = $today;
                $order['order_auth_end'] = date("Y-m-d",strtotime("+$many month"));
            }
            //-----------ios的支付id----------------------
            $iphone_id = Db::table('up_member_price')
                ->where('mp_auth',$authtype)
                ->where('mp_phone',2)
                ->value('mp_ios_id');
        }else{
            $money = Db::table('up_top_bag')
                ->where('t_b_id',$which+1)
                ->value('t_b_price');
            $order['order_money'] = $money;
            //-----------ios的支付id----------------------
            $iphone_id = $money = Db::table('up_top_bag')
                ->where('t_b_id',$which+1)
                ->value('t_b_iosid');
        }
        $res = Db::table('up_order')->insert($order);
        if($res){
            return json_encode(['status'=>200,'msg'=>$iphone_id,'order_number'=>$order['order_number']]);
        }else{
            return json_encode(['status'=>0,'msg'=>'订单生成失败']);
        }
    }

}